/**
 * Created by Ding on 2016/4/8.
 * Copyright (c) 2016, auais.com All Rights Reserved.
 * File Name:
 * Package Name:
 * Date:2016/4/8 11:23
 */
    'use strict';
const ObjectID = require('mongodb').ObjectID;
const mongo = require('mongodb');
const GridStore = require('mongodb').GridStore;
const fs = require("fs");
const path = require('path');
const Grid = require('gridfs-stream');
const Busboy = require('busboy');
const inspect = require('util').inspect;
const gm = require("gm");
module.exports = {
    handler: (req, res, next)=>{
        console.log( "!!!!!!!!!!!!!!!!!!!",req.get('content-type'));
        req.context=req.context||{};
        const userId=req.context.user||new ObjectID(0);
        const versionNum = req.query.version||'';
        const gfs = Grid(req.mongo, mongo);
        const busboy = new Busboy({headers: req.headers});



        req.mongo.collection("exeFile").find({client:true}).toArray((e,r)=>{
            if(e) return res.err.unknownError(err);

            let clientInfo = r[0];
            //第三方中间件接收上传
            req.pipe(busboy);
            busboy.on('file', function (fieldname, file, filename, encoding, mimetype) {
                //var ext = path.extname(filename).toLowerCase();
                var filesize = 0;
                const id = new ObjectID();
                console.log("############################",fieldname, file, filename, encoding, mimetype);
                const writestream = gfs.createWriteStream({
                    _id: id,
                    mode: "w",
                    filename: filename,
                    content_type: mimetype
                });
                file.pipe(writestream);

                file.on('end', function () {
                    console.log("end");
                    const url = "/res/" + id+"/content";
                    const fileObj = {
                        id: id,
                        filename: filename,
                        content_type: mimetype,
                        filesize: filesize,
                        url: url
                    };
                    res.json(fileObj);
                    //将资源记录用户表
                    var fn = function (e,r) {
                        console.log("insert====================",e,r);
                    };

                    let insertClientInfo ={
                        _id: id,
                        "userId": userId,
                        "version": versionNum,
                        filename: fileObj.filename,
                        "url": "/res/" + id + "/content",
                        client:true,
                        "uploadTime": new Date()
                    };
                    if(clientInfo){
                        insertClientInfo.cnt = clientInfo.cnt;
                        req.mongo.collection("exeFile").insertOne(insertClientInfo, (e,r)=>{
                            console.log("update========================",e,r);
                            gfs.remove({_id:clientInfo._id}, function (err) {
                                console.log("删除资源==========");
                            });
                            req.mongo.collection("exeFile").removeOne({_id:clientInfo._id},fn);
                        });

                    }else{
                        insertClientInfo.cnt = 0;
                        req.mongo.collection("exeFile").insertOne(insertClientInfo,fn);
                    }
                }).on('error', function (err) {
                    console.log("err:" + err)
                }).on('data', function (data) {
                    filesize += data.length;
                    //   console.log(filesize);
                });

            })
        });

    }
};